
import {ChangeDetectorRef, Component} from "@angular/core";
import {NavController, NavParams, AlertController, ToastController, ActionSheetController} from "ionic-angular";
import {HttpService} from "../../../providers/http.service";
import {CommonFunc} from "../../../providers/commonFunc";
import {HomePage} from "../../home/home";
import { Storage } from "@ionic/storage";
import {Camera, CameraOptions} from "@ionic-native/camera";
import {FileTransfer, FileTransferObject, FileUploadOptions} from "@ionic-native/file-transfer";
import {appConfig} from "../../../providers/config";
import {PhotoViewer} from "@ionic-native/photo-viewer";
/**
 * 已经完成电梯检查列表
 */
@Component({
  templateUrl: "finish-check-list.html"
})
export class FinishCheckList {
    // 定义检查Id
    public checkerId: any = null;
    // 定义名称
    public checkerName:any=null;
    // 定义登录者数据
    public dataParm:any;
    // 定义登录者类型
    public partyType:any;
    // 定义步伐
    public temp:any
    // 定义返回结果
    public finishList:any=[];

    private appConfig: any;

    constructor(
        private navParams: NavParams,
        private commonFunc: CommonFunc,
        private httpService: HttpService,
        private storage: Storage,
        private camera: Camera,
        private transfer: FileTransfer,
        private navCtrl: NavController,
        public cd: ChangeDetectorRef,
        private ActionSheet: ActionSheetController,
        private photoViewer: PhotoViewer,
        public alertCtrl: AlertController,
        private toast: ToastController

    ) {
        this.appConfig = appConfig;


    }
    ionViewWillEnter() {
        this.storage.get("user").then(data => {
            // 获取数据
            this.dataParm = data;
            this.partyType = data.partyType;

            this.checkerId = data.id;
            this.checkerName = data.userName;
            if(this.dataParm !=null && this.dataParm !=undefined){
                this.findFinishList();
            }
        });

    }
    accordion(index,temp) {
        this.temp=temp+index;
    }
    // 查询数据
    findFinishList() {
        if (this.dataParm.partyType == '1') {
            let userId = this.dataParm.id;
            // 未检查为1
            this.httpService.queryFinishRecord({"userId": userId, "checkRecord": 1}).subscribe(data => {
                if (data.status != 200) {
                    let toast = this.commonFunc.showInsideErrorToast(data);
                    toast.present();
                    return;
                }
                this.finishList = data.data;
            });
        }
    }

    doCamera(index, i) {
        let options: CameraOptions = {
            quality: 85, // destinationType: this.camera.DestinationType.DATA_URL,
            // encodingType: this.camera.EncodingType.JPEG,
            mediaType: this.camera.MediaType.PICTURE,
            targetWidth: 1500,
            targetHeight: 1500,
            correctOrientation: true
        };
        this.camera.getPicture(options).then(imageData => {
            //判断网络状态
            console.log("判断网络状态");
            if (!this.commonFunc.hasNetWork()) {
                if (i == 'c') {
                    console.log("c")
                    this.finishList[index].result.picUrl.push(imageData);
                } else {
                    console.log(" ! c")
                    this.finishList[index].result.picUrl[i] = imageData;
                }
                return;
            }
            const options: FileUploadOptions = {};
            let serverUrl = encodeURI(appConfig.IP_URL + appConfig.API.upload);
            //let serverUrl =  encodeURI('http://192.168.43.242:8080/upload/base.ctrl');
            options.fileKey = 'file';
            options.fileName = 'test.jpg';
            options.mimeType = 'image/jpeg';
            const fileTransfer: FileTransferObject = this.transfer.create();
            fileTransfer.upload(imageData, serverUrl, options).then(restul => {
                let aa = JSON.parse(restul['response']);
                console.log("输出aa");
                console.log(aa);
                if (aa['status'] == 200) {
                    if (aa['data'].length > 0) {
                        if (i == 'c') {
                            console.log("c")
                            console.log(aa['data']);
                            this.finishList[index].result.picUrl.push(aa['data']);

                        } else {
                            console.log("!c")
                            this.finishList[index].result.picUrl[i] = aa['data'];
                        }
                    }
                }
                this.cd.detectChanges();
            });
        });
    }

    onHold(index, param) {
        let actionSheet = this.ActionSheet.create({
            buttons: [
                {
                    text: '重拍',
                    role: '重拍',
                    handler: () => {
                        let i = this.finishList[index].result.picUrl.indexOf(param);
                        this.doCamera(index, i);
                    }
                },
                {
                    text: '查看大图',
                    role: '查看大图',
                    handler: () => {
                        this.photoViewer.show(
                            encodeURI(this.whaturl(param)).replace('%5C', '/'),
                            null,
                            {
                                share: false
                            }
                        );
                    }
                },
                {
                    text: '删除',
                    handler: () => {
                        let i = this.finishList[index].result.picUrl.indexOf(param);
                        this.finishList[index].result.picUrl.splice(i, 1);
                    }
                },
                {
                    text: '取消',
                    role: '取消',
                    handler: () => {
                        //console.log('Cancel clicked');
                    }
                }
            ]
        });
        actionSheet.present();
    }

    whaturl(url) {
        if ((url + '').indexOf('file') < 0) {
            return this.appConfig.IP_URL + this.appConfig.API.getUpload + url;
        } else {
            return url;
        }
    }
}
